import * as echarts from '../../3rd/ec-canvas/echarts';
import {
  BASE_DIR
} from '../../utils/consts';

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    winWidth: 0,
    winHeight: 0,
    currentTab: 0,
    title: ['年', '月', '日', '时'],
    name: '',
    gender: '',
    input: '',
    geju: '',
    yong_shen: '',
    xi_shen: '',
    relationships: '',
    dayun: null,
    liunian: null,
    dyln_relationships: '',
    pan: [],
    rpt_id: null,
    pie: {
      lazyLoad: true
    },
    energy_list: [0, 0, 0, 0, 0],
    ten_year: '',
    year: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this;
    wx.getSystemInfo({
      success: function (res) {
        self.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight,
          rpt_id: options.id,
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.pie_dom = this.selectComponent('#pie')
    this.loadData()
  },
  loadData: function () {
    let self = this;
    wx.request({
      url: BASE_DIR + '/report/' + self.data.rpt_id + '/',
      header: {
        'Authorization': 'bazi ' + app.globalData.userInfo.openid
      },
      success: function (res) {
        let resp = res.data.data;
        self.setData({
          name: resp.name,
          gender: resp.gender,
          input: resp.input,
          pan: [
            [
              ['干神'], ...resp.report.gans_shen
            ],
            [
              ['天干'], ...resp.report.gans
            ],
            [
              ['地支'], ...resp.report.zhis
            ],
            [
              ['藏干'], ...resp.report.cang_gans
            ],
            [
              ['支神'], ...resp.report.zhis_shen
            ],
            [
              ['长生'], ...resp.report.zhangsheng
            ],
            [
              ['自坐'], ...resp.report.self_zs
            ],
            [
              ['禄位'], ...resp.report.lushen_zhis
            ],
            [
              ['纳音'], ...resp.report.nayin
            ],
            [
              ['神煞'], ...resp.report.shensha
            ],
          ],
          geju: resp.report.geju,
          yong_shen: resp.report.yong_shen,
          xi_shen: resp.report.xi_shen,
          relationships: resp.report.relationships.join(', '),
          dyln_relationships: resp.report.dyln_relationships && resp.report.dyln_relationships.join(', '),
          dayun: resp.report.dayun,
          liunian: resp.report.liunian,
        })
        let angle_data = ['木', '火', '土', '金', '水'
          // '木(' + resp.report.roles['木'] + ')',
          // '火(' + resp.report.roles['火'] + ')',
          // '土(' + resp.report.roles['土'] + ')',
          // '金(' + resp.report.roles['金'] + ')',
          // '水(' + resp.report.roles['水'] + ')',
        ];
        let energy_list = [
          resp.report.energy['木'] || 0,
          resp.report.energy['火'] || 0,
          resp.report.energy['土'] || 0,
          resp.report.energy['金'] || 0,
          resp.report.energy['水'] || 0
        ];
        let total = 0
        for (let i=0; i<energy_list.length; i++) {
          total += energy_list[i];
        }
        let sum = 0
        for (let i=0; i < energy_list.length; i++){
          if (i < 4){
            energy_list[i] = parseInt(energy_list[i]*100/total + 0.5)
            sum += energy_list[i]
          } else{
            energy_list[i] = 100-sum
          }
        }

        self.setData({
          energy_list: energy_list
        })
  
        const opts = {
          title: {
            text: resp.report.title,
            left: 'center',
          },
          polar: {
            radius: [0, '80%']
          },
          radiusAxis: {
            axisLine: {show: false}
          },
          angleAxis: {
            data: angle_data,
          },
          series: {
            type: 'pie',
            roseType: 'area',
            coordinateSystem: 'polar',
            label: {show: false},
            data: [{
              value: parseInt(energy_list[0]),
              name: angle_data[0],
              itemStyle: {
                color: "#298b64"
              }
            }, {
              value: parseInt(energy_list[1]),
              name: angle_data[1],
              itemStyle: {
                color: "#ee2e2f"
              }
            }, {
              value: parseInt(energy_list[2]),
              name: angle_data[2],
              itemStyle: {
                color: "#bd7334"
              }
            }, {
              value: parseInt(energy_list[3]),
              name: angle_data[3],
              itemStyle: {
                color: "#fb8d22"
              }
            }, {
              value: parseInt(energy_list[4]),
              name: angle_data[4],
              itemStyle: {
                color: "#0d66d7"
              }
            }],
          }
        }
        console.log('opts', JSON.stringify(opts));
        if (self.chartPie) {
          self.chartPie.setOption(opts)
        } else {
          self.initPie(opts)
        }
      }
    })
  },
  initPie: function (options) {
    this.pie_dom.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr
      });
      chart.setOption(options)

      this.chartPie = chart
      return chart
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},

  onDayunTap: function (e) {
    let self = this;
    let val = e.target.dataset.val;
    wx.request({
      url: BASE_DIR + '/report/' + self.data.rpt_id + '/dyln/?dayun=' + val,
      header: {
        'Authorization': 'bazi ' + app.globalData.userInfo.openid
      },
      success: function (res) {
        let resp = res.data.data;
        self.setData({
          ten_year: resp.ten_year,
          dayun: resp.dayun,
          liunian: resp.liunian,
          dyln_relationships: resp.dyln_relationships.join(', ')
        })
      }
    })
  },
  onLiunianTap: function (e) {
    let self = this;
    let val = e.target.dataset.val;
    wx.request({
      url: BASE_DIR + '/report/' + self.data.rpt_id + '/dyln/?dayun=' + self.data.ten_year + '&liunian=' + val,
      header: {
        'Authorization': 'bazi ' + app.globalData.userInfo.openid
      },
      success: function (res) {
        let resp = res.data.data;
        self.setData({
          ten_year: resp.ten_year,
          year: resp.year,
          dayun: resp.dayun,
          liunian: resp.liunian,
          dyln_relationships: resp.dyln_relationships.join(', ')
        })
      }
    })
  },
  ontdTap: function (e) {
    let cate = e.target.dataset.cate;
    let val = e.target.dataset.val;
    console.log('ontdTap', cate, val);
    if (cate == '藏干') {
      wx.navigateTo({
        url: '/pages/canggan/canggan'
      })
    } else if (cate == '干神' || cate == '支神') {
      wx.navigateTo({
        url: '/pages/shishen/shishen'
      })
    } else if (cate == '长生' || cate == '自坐' || cate == '禄位') {
      wx.navigateTo({
        url: '/pages/zhangsheng/zhangsheng'
      })
    } else if (cate == '神煞') {
      if (val === cate) {
        wx.navigateTo({
          url: '/pages/shenshas/shenshas'
        })
      }else{
        wx.navigateTo({
          url: '/pages/shensha/shensha?name=' + val
        })
      }
    }
  }
})